<template>
  <el-drawer :visible.sync="visible" size="500px" :show-close="false" ref="drawer">
    <template v-if="init">
      <div class="header-title" :class="`header-title-${type}`" slot="title">
        <span>{{$t('calendar.detail.agendaDetail')}}</span>
        <div class="opt">
          <!-- <i class="iconfont icon-bell"></i>  -->
          <!--<template v-show="detail.inApprove != 1 && detail.isPaused != 1">
            <el-tooltip content='编辑' placement='top'>
              <i v-show="canEdit" class="iconfont icon-edit-square" @click="edit"></i> 
            </el-tooltip> 
            <el-tooltip content='删除' placement='top'>
              <i v-show="canDel" class="iconfont icon-delete" @click="del"></i> 
            </el-tooltip> 
          </template>-->
          <i class="iconfont icon-yemianshanchu" @click="close"></i> 
        </div>
      </div>

      <div class="content">
        <p><i class="iconfont icon-fdn-datetime"></i> {{detail.planStartTime | fmt_datetime}} {{$t('common.base.to')}} {{detail.planEndTime | fmt_datetime}}</p>
        <p><i class="iconfont icon-fdn-user"></i><span class="task-pointer" v-user="detail.createUserId"><img :src="head(detail.createUserHead)" /></span>
          <template v-if="isOpenData && detail.createUserStaffId">
            <open-data :openid="detail.createUserStaffId"></open-data>{{$t('common.base.create3')}}
          </template>
          <template v-else>
            {{$t('calendar.detail.creater', {createUserName: detail.createUserName ? detail.createUserName : detail.source})}}
          </template> 
        </p>
      </div>

      <!-- 事件信息 -->
      <div class="list-item" @click="openTab(detail.id)">
        <!-- 事件卡片底部 -->
        <div class="item-bottom">
          <div class="item-info">
            <div class="item-info-left">
              <div class="task-item-customer">
                <h4>{{detail.eventNo}}</h4>
                <p class="customer-name">
                  {{$t('common.form.type.customerName')}}：{{detail.cusName}}</p>
                <p class="task-content-address">
                  {{$t('common.base.address')}}：{{detail.cusAddress | fmt_address}}
                </p>
                <p class="task-content-address">
                  {{$t('common.base.column.createTime')}}：{{detail.createTime | fmt_datetime}}
                </p>
              </div>
            </div>
            <span class="event-state" :style="{color: color(detail.state)}">{{stateText(detail.state)}}</span>
          </div>
        </div>
      </div>
      <div class="content">
        <p class="mb-5"><i class="iconfont icon-fdn-user"></i> {{$t('common.fields.executorUser.displayName')}}</p>
        <el-tag disable-transitions type='info' size="medium">
          <span class="task-pointer" v-user="detail.executorId">
            <img :src="head(detail.executorHead)">
            <template v-if="isOpenData && detail.executorStaffId">
              <open-data :openid="detail.executorStaffId"></open-data>
            </template>
            <template v-else>
              {{detail.executorName}}
            </template>
          </span>
        </el-tag>
      </div>
      <div v-if="detail.synergies && detail.synergies.length" class="content">
        <p class="mb-5"><i class="iconfont icon-fdn-user"></i> {{$t('common.fields.synergies.displayName')}}</p>
        <el-tag :key="user.userId" v-for="user in detail.synergies" disable-transitions type='info' size="medium">
          <span class="task-pointer" v-user="user.userId">
            <img :src="head(user.head)">
            <template v-if="isOpenData && user.staffId">
              <open-data :openid="user.staffId"></open-data>
            </template>
            <template v-else>
              {{user.displayName}}
            </template>
          </span>
        </el-tag>
      </div>
      <el-tabs>
        <el-tab-pane :label="$t('common.base.dynamicInfo')">
          <event-progress-rate v-if="initData && visible" ref="eventProgressRate" :event="detail" :init-data="initData" :agenda-event="true"></event-progress-rate>
        </el-tab-pane>
      </el-tabs>
    </template>
  </el-drawer>

</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import AuthUtil from '@src/util/auth';
import * as EventApi from '@src/api/EventApi.js';
import * as CalendarApi from '@src/api/CalendarApi.ts'
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import EventProgressRate from '@src/modules/event/eventDetailView/components/ContactInfo/EventProgressRate.vue'
import EventStateEnum from '@model/enum/EventStateEnum.ts';
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
let colorMap = {
  created: '#FA8C16',
  allocated: '#FA8C16',
  processing: '#FFAE00',
  finished: '#67C23A'
}
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
export default {
  name: 'agenda-task-detail',
  props: {
    eventId: {
      type: [Number, String],
      default: '',
    },
    type: {
      type: [Number, String],
      default: 1,
    },
  },
  components: {
    EventProgressRate,
  },
  data() {
    return {
      isOpenData,
      initData: null,
      auth: {},
      pending: false,
      visible: false,
      detail: {},
      init: false,
      recordList: [],
    }
  },
  computed: {
    canEdit() {
      return this.initData?.canEdit
    },
    canDel() {
      return AuthUtil.hasAuth(this.auth, 'CASE_DELETE') && this.canEdit;
    },
  },
  methods: {
    stateText(state) {
      return EventStateEnum.getName(state);
    },
    color(state){
      return colorMap[state];
    },
    openTab(id) {
      // 跳转到事件详情页面
      let fromId = window.frameElement.getAttribute('id')
      // this.$platform.openTab({
      //   id: `event_view_${id}`,
      //   title: '事件详情',
      //   close: true,
      //   url: `/event/view/${id}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: id,
        fromId
      })
      this.visible = false
    },
    // 打开重新获取数据 不进行缓存
    showDetail(eventId) {
      if (eventId) {
        // this.queryInitData()
        this.getAgendaInfo(eventId)
      }
      this.visible = true;
    },
    edit() {
      this.close()
      // 跳转到事件编辑页面
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'eidtEvent',
      //   title: '编辑事件',
      //   url: `/event/edit/${this.eventId}?agendaEvent=true`,
      //   close: true,
      //   fromId,
      // });

      openAccurateTab({
        type: PageRoutesTypeEnum.PageEditEvent,
        key: this.eventId,
        params: 'agendaEvent=true',
        fromId
      })
    },
    del() {
      this.close()
      this.$emit('del', this.eventId, this.detail.state)
    },
    close() {
      this.$refs.drawer.closeDrawer()
    },
    head(src) {
      if (!src) return defaultAvatar
      return src
    },
    // 获取日程详情
    async getAgendaInfo(eventId) {
      if(!eventId) return
      try {
        const res = await CalendarApi.getEventAgendaInfo({ eventId })
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          })
        }
        if(!this.init) this.init = true
        this.detail = res.data?.workEvent || {}
        if(this.detail.planStartTime) this.detail.planStartTime = formatDate(safeNewDate(this.detail.planStartTime), 'yyyy-MM-dd HH:mm')
        if(this.detail.planEndTime) this.detail.planEndTime = formatDate(safeNewDate(this.detail.planEndTime), 'yyyy-MM-dd HH:mm')
        
        this.initData = res.data || {}
        this.auth = JSON.parse(this.initData.auth) || {}
      } catch (err) {
        console.error('err', err)
      }
    },
    // 获取事件动态
    getEventRecord() {
      const params = {
        eventId: this.eventId,
        pageNum: 1,
        pageSize: 99999,
      }
      EventApi.getEventRecord(params).then(res=> {
        this.recordList = res || []
      })
    },
    renderRecord(h, item) {
      return <p>{item.content}</p>
    },
    async accept(status) {
      try {
        this.pending = true
        const res = await CalendarApi.setAgendaUserStatus({
          agendaId: this.agendaId,
          status,
        })
        this.pending = false
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          })
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.operationSuccess'),
          type: 'success',
        })
        this.getAgendaInfo(this.eventId)
      } catch (err) {
        this.pending = false
        console.error('err', err)
      }
    },
    async addAgendaUsers(users) {
      try {
        const res = await CalendarApi.addAgendaUser({
          agendaId: this.agendaId,
          users,
        })
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          })
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.operationSuccess'),
          type: 'success',
        })
        this.getAgendaInfo(this.eventId)
      } catch (err) {
        console.error('err', err)
      }
    },
    async delAgendaUser(userId) {
      try {
        const res = await CalendarApi.delAgendaUser({
          agendaId: this.agendaId,
          userId,
        })
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          })
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.operationSuccess'),
          type: 'success',
        })
        this.getAgendaInfo(this.eventId)
      } catch (err) {
        console.error('err', err)
      }
    },
    selectApproveUser() {
      // let selected = this.users.map(item=>{
      //   item.displayName = item.userName
      //   item.head = item.userHead
      //   return item
      // });
      let selected = []
      let options = {
        title: this.$t('calendar.detail.selectParticipants'), // [选填] 默认值为 '请选择人员'
        max: -1, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        unique: false,
        haveRole: true,
        mode: BaseSelectUserModeEnum.Filter
      }

      this.$fast.select.multi.user(options)
        .then((res) => {
          // console.info('res:', res)
          if (res.status != 0 || !res.data) return
          let list = res.data.users || []
          // const userIds = [...this.users, ...list].map(item=>item.userId)
          // this.addAgendaUsers([...new Set(userIds)])
          const userIds = list.map((item) => item.userId)
          this.addAgendaUsers(userIds)
        })
        .catch((err) => {
          console.warn(err)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-drawer__header {
  padding: 0;
  margin-bottom: 0px;
  box-sizing: border-box;
}

::v-deep .el-drawer__body {
  overflow-y: scroll;
  margin-top: 10px;
}

.header-title {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  color: #fff;
  i {
    margin-left: 15px;
  }
}

.header-title-2 {
  background: $color-primary-light-6;
}
.header-title-1 {
  background: #faae14;
}
.header-title-3 {
  background: rgb(76, 175, 80);
}

.content {
  padding: 0 20px;
  margin-bottom: 10px;
  img {
    height: 30px;
    width: 30px;
    border-radius: 50%;
    margin-right: 4px;
    object-fit: cover;
  }
  p {
    display: flex;
    align-items: center;
  }
  i {
    font-size: 16px;
    margin-right: 5px;
  }
  .notice-content {
    margin-left: 20px;
  }
}
.mb-5{
  margin-bottom: 5px;
}
.agenda-users {
  ::v-deep .el-tabs__content {
    display: flex;
    .add-user {
      padding: 4px 10px;
      border: 1px dashed;
      border-radius: 4px;
      margin-left: 20px;
      margin-right: -5px;
    }
    .el-tag {
      border-radius: 4px;
      margin-bottom: 12px;
    }
  }
}

::v-deep .el-tabs {
  margin-bottom: 10px;
  .el-tabs__active-bar {
    height: 0;
  }
  .el-tabs__nav-wrap {
    // background: #f5f5f5;
    padding-left: 20px;
    border-bottom: 1px solid #e8e8e8;
  }
  .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
  .progress-content{
    padding: 0;
  }
}

.el-tag {
  margin-left: 12px;
  border-radius: 4px;
  color: #666;
  margin-bottom: 10px !important;
  img {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin-bottom: 1px;
    object-fit: cover;
  }
}

.base-timeline {
  margin-bottom: 20px;
}

.btn-group {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100%;
  padding: 10px;
  background: #f5f5f5;
  text-align: right;
}

.list-item {
  position: relative;
  margin: 20px;
  // background: #f5f5f5;
  border-radius: 12px;
  background: #FAFAFA;
  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.12);
  .item-top {
    position: relative;
    display: flex;
    flex-direction: column;
    padding: 12px 10px;
    border-bottom: 0.5px solid #e8e8e8;

    .item-top-left {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      width: 100%;

      // max-width: calc(100% - 65px);
      .item-top-left-text {
        flex: 1;
        display: flex;
        // align-items: center;
        margin-bottom: 4px;

        .item-priority {
          border: 1px solid #afb5b3;
          display: inline-block;
          padding: 1px 4px;
          margin-left: 5px;
          font-size: 12px;
          font-weight: bold;
          color: #afb5b3;
          border-radius: 2px;
          height: 17px;
          line-height: 14px;
          margin-top: 2px;
          max-width: 50px;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
          white-space: normal;
          word-wrap: break-word;
          word-break: break-all;
        }

        .high {
          color: #ff4d4f;
          border: 1px solid rgba(251, 96, 44, 0.32);
        }

        .middle {
          color: #ffae00;
          border: 1px solid rgba(255, 147, 0, 0.32);
        }

        .low {
          color: #6ecf40;
          border: 1px solid rgba(110, 207, 64, 0.32);
        }
      }

      h3 {
        font-size: 16px;
        color: #262626;
        margin: 0;

        .item-priority {
          background: #afb5b3;
          color: #afb5b3;
          border: 1px solid rgba(175, 181, 179, 0.32);
        }
      }

      p {
        height: 20px;
        line-height: 20px;
        color: #595959;
        // font-size: 13px;
        margin: 0;
        padding-top: 5px;
      }
    }
  }

  .item-bottom {
    padding: 5px 10px 10px 10px;

    .item-info {
      display: flex;
      position: relative;

      .item-info-left {
        flex: 1;
        width: calc(100% - 76px);
        padding-bottom: 5px;
        color: #595959;

        p {
          //height: 20px;
          line-height: 20px;
          // font-size: 13px;
          margin: 0 0 4px 0;

          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        .task-item-customer {
          h4 {
           color: $color-primary-light-6;
           cursor: pointer;
          }
          margin-top: 6px;
          margin-bottom: 4px;

          .customer-name {
            max-width: 200px;
          }
        }

        .task-content {
          color: #595959;
          height: auto;
          max-height: 40px;
        }

        .task-content-address {
          color: #595959;
          max-height: 40px;
          @include text-ellipsis-2;
          word-break: break-all;
        }

        .item-states-new {
          display: inline-block;
          background: #fff !important;
          color: $color-danger;
          border: 1px solid rgba(251, 96, 44, 0.32);
          margin: 2px 0 !important;
          font-size: 12px;
          padding: 1px 4px;
          margin-right: 5px !important;
          font-weight: bold;
          border-radius: 2px;
          height: 21px;
          line-height: 18px;
        }
      }
    }
  }
}
</style>